<template>
  <div class="main-menu">
    <div class="logo">
      <img src="../../../assets/img/avater.png" alt="logo" />
      <span class="title">亿数管理系统</span>
    </div>
    <el-menu
      :default-active="defaultActive"
      :collapse="!isExpand"
      class="el-menu-vertical-demo"
    >
      <template v-for="item in menus" :key="item.menuId">
        <el-sub-menu :index="item.menuId + ''" v-if="item.children">
          <template #title>
            <el-icon>
              <component :is="item.icon.split('-icon-')[1]" />
            </el-icon>
            <span>{{ item.name }}</span>
          </template>
          <template v-for="subitem in item.children" :key="subitem.menuId">
            <el-menu-item
              :index="subitem.menuId + ''"
              @click="clickMenu(subitem.path)"
              >{{ subitem.name }}</el-menu-item
            >
          </template>
        </el-sub-menu>

        <el-menu-item
          :index="item.menuId + ''"
          v-else
          @click="clickMenu(item.path)"
        >
          <template #title>
            <el-icon>
              <component :is="item.icon.split('-icon-')[1]" />
            </el-icon>
            <span>{{ item.name }}</span>
          </template>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script lang="ts" setup>
import router from '@/router'
import useLoginStore from '@/store/login/loginstore'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

defineProps({
  isExpand: {
    type: Boolean,
    default: true
  }
})
const defaultActive = ref('1')
const loginStore = useLoginStore()
const menus = loginStore.menus

const route = useRoute()

function clickMenu(path: string) {
  router.push(path)
}

const findActiveItemByPath = (path: string) => {
  for (const item of menus) {
    if (item.path === path) {
      defaultActive.value = item.menuId + ''
    }
    if (item.children) {
      for (const child of item.children) {
        if (child.path === path) {
          defaultActive.value = child.menuId + ''
        }
      }
    }
  }
}

findActiveItemByPath(route.path)

watch(
  () => route.path,
  (newPath) => {
    findActiveItemByPath(newPath)
  }
)
</script>

<style scoped lang="scss">
.el-menu {
  border-right: none;
}

.logo {
  display: flex;
  align-items: center;
  padding: 20px;
  width: 100%;
  height: 80px;

  img {
    margin-right: 10px;
    // width: 50px;
    height: 100%;
  }

  .title {
    font-size: 18px;
    font-weight: 600;
    white-space: nowrap;
  }
}
</style>
